<template>
  <items-card></items-card>
  <div class="info-section">
    <p>工单ID: {{ orderId }}</p>
    <p>工单号: {{ orderNumber }}</p>
    <p>实际数量: {{ actualQuantity }}</p>
    <p>产品名称: {{ productName }}</p>
  </div>
  <div class="app-container">
    <el-alert
        v-if="errorMessage"
        :title="errorMessage"
        type="error"
        show-icon
        class="error-alert"
    />
    <el-table v-loading="loading" :data="inventoryList" empty-text="暂无数据">
      <el-table-column label="产品ID" align="center" prop="productId" />
      <el-table-column label="工单排行" align="center" prop="orderNum" />
      <el-table-column label="检验项目" align="center">
        <template #default="{row}">
          <el-select
              v-model="row.selectedItems"
              multiple
              placeholder="请选择检验项目"
              @change="handleItemChange(row)"
          >
            <el-option
                v-for="item in inspectionItems"
                :key="item.itemId"
                :label="item.name"
                :value="item.itemId"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="详细描述" align="center">
        <template #default="{row}">
          <el-input
              v-model="row.defect_description"
              type="textarea"
              placeholder="输入“无”为合格"
          />
        </template>
      </el-table-column>
      <!-- 添加这个属性允许多文件上传 -->
      <el-table-column label="图片" align="center">
        <template #default="{row}">
          <el-upload
              action="#"
              list-type="picture-card"
              :auto-upload="false"
              :on-change="(file) => handleFileChange(file, row)"
              multiple
              :file-list="row.fileList || []"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </template>
      </el-table-column>
      <el-table-column label="检验时间" align="center" prop="inspection_time">
        <template #default="{row}">
          <el-date-picker
              v-model="row.inspection_time"
              type="datetime"
              placeholder="选择检验时间"
          />
        </template>
      </el-table-column>
    </el-table>

    <div class="action-buttons">
      <el-button type="primary" @click="handleSubmit" :loading="submitting">提交</el-button>
      <el-button @click="handleBack">返回</el-button>
    </div>
  </div>
</template>

<script setup>
import {useRoute, useRouter} from 'vue-router'
import {ref, onMounted} from 'vue'
import {checkList} from "@/api/material-service/inventory"
import { addResults } from "@/api/quality-service/results"
import { updateOrders } from "@/api/workorder-service/orders" // 新增导入
import ItemsCard from "@/views/quality-service/items/itemsCard.vue";
import { ElMessage } from 'element-plus'

import useUserStore from "@/store/modules/user.js";
const userStore = useUserStore()
const route = useRoute()
const router = useRouter()
const {proxy} = getCurrentInstance()

const orderId = route.query.orderId
const orderNumber = route.query.orderNumber
const actualQuantity = parseInt(route.query.actualQuantity) || 0
const productName = route.query.productName

// 检验项目选项
const inspectionItems = ref([
  {itemId: 'QITEM001_MAT1', name: '钢板厚度'},
  {itemId: 'QITEM001_OP5', name: '喷涂厚度'},
  {itemId: 'QITEM001_PROD', name: '外观划痕'},
  {itemId: 'QITEM002_PROD', name: '尺寸一致性(高度)'}
])

const inventoryList = ref([])
const loading = ref(false)
const submitting = ref(false)
const errorMessage = ref('')

// 生成5个不重复的随机序号
function generateRandomOrderNums() {
  const nums = new Set()
  while (nums.size < 5 && nums.size < actualQuantity) {
    const randomNum = Math.floor(Math.random() * actualQuantity) + 1
    nums.add(randomNum)
  }
  return Array.from(nums)
}

// 处理检验项目选择变化
function handleItemChange(row) {
  row.item_id = row.selectedItems.join(',')
}

// 处理文件上传
function handleFileChange(file, row) {
  // 这里可以处理文件上传逻辑，实际项目中可能需要调用上传API
  // 这里简单地将文件路径存储到行数据中
  row.defect_image_url = URL.createObjectURL(file.raw)
}

// 返回上一页
function handleBack() {
  router.go(-1)
}

// 提交表单
async function handleSubmit() {
  try {
    submitting.value = true

    // 验证数据
    const invalidRows = inventoryList.value.filter(row => {
      return !row.selectedItems || row.selectedItems.length === 0 ||
          !row.defect_description || !row.inspection_time
    })

    if (invalidRows.length > 0) {
      ElMessage.error('请填写完整的检验信息（检验项目、详细描述、检验时间）')
      return
    }

    // 准备提交数据
    const submitPromises = inventoryList.value.map(row => {
      const submitData = {
        orderId: orderId,
        itemId: row.item_id, // 多个检验项目ID用逗号分隔
        sampleIndex: row.orderNum, // 使用工单排行作为样本序号
        defectDescription: row.defect_description,
        defectImageUrl: row.defect_image_url,
        inspectionTime: row.inspection_time,
        inspectorId: userStore.id, // 这里应该替换为实际的用户ID
      }
      return addResults(submitData)
    })

    await Promise.all(submitPromises)

    // 更新工单状态为完成
    await updateOrders({
      id: orderId,
      status: 5 // 5 对应完成状态
    })

    ElMessage.success('提交成功，工单状态已更新为完成')
    // 跳转到质量检验结果列表页
    router.push('/quality/results')
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败: ' + (error.message || '未知错误'))
  } finally {
    submitting.value = false
  }
}

//查询列表
async function getList() {
  try {
    loading.value = true
    errorMessage.value = ''
    inventoryList.value = []

    const orderNums = generateRandomOrderNums()

    // 带重试机制的请求
    const res = await retryRequest(
        () => checkList({
          orderId: orderNumber,
          orderNums: orderNums
        }),
        3, // 最大重试次数
        1000 // 重试间隔
    )

    if (res.data?.length > 0) {
      inventoryList.value = res.data.map((item, index) => ({
        ...item,
        id: index + 1,
        selectedItems: [], // 用于存储选中的检验项目
        item_id: '', // 实际存储的检验项目ID，用逗号分隔
        defect_description: '', // 缺陷描述
        defect_image_url: '', // 图片URL
        inspection_time: new Date() // 默认当前时间为检验时间
      }))
    } else {
      errorMessage.value = '未查询到有效数据'
    }
  } catch (error) {
    console.error('最终请求失败:', error)
    errorMessage.value = `请求失败: ${error.message}`
  } finally {
    loading.value = false
  }
}

// 重试工具函数
async function retryRequest(requestFn, maxRetries = 3, delay = 1000) {
  let lastError;
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await requestFn()
    } catch (error) {
      lastError = error
      if (i < maxRetries - 1) {
        await new Promise(resolve => setTimeout(resolve, delay))
      }
    }
  }
  throw lastError
}

onMounted(() => {
  if (orderId && actualQuantity > 0) {
    getList()
  } else {
    errorMessage.value = "缺少必要的工单信息"
  }
})
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
  margin-top: 20px;
}

.info-section {
  padding: 15px;
  margin: 20px;
  background: #f5f7fa;
  border-radius: 4px;

  p {
    margin: 8px 0;
    font-size: 14px;
    color: #606266;

    &:first-child {
      margin-top: 0;
    }

    &:last-child {
      margin-bottom: 0;
    }
  }
}

.error-alert {
  margin-bottom: 20px;
}

/* 调整表格内元素样式 */
:deep(.el-table .cell) {
  .el-select, .el-input, .el-date-editor {
    width: 100%;
  }

  .el-textarea {
    width: 100%;

    :deep(.el-textarea__inner) {
      min-height: 60px;
    }
  }
}

.action-buttons {
  margin-top: 20px;
  text-align: center;

  .el-button {
    margin: 0 10px;
  }
}
</style>